package com.sysu.homework.action;

import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.sysu.homework.model.Group;
import com.sysu.homework.model.Student;
import com.sysu.homework.service.StudentService;

@Component("createGroupAction")
@Scope("prototype")
public class CreateGroupAction extends ActionSupport{
	private String name;
	private String description;
	
	private StudentService studentService;

	@Override
	public String execute() throws Exception {
		HttpSession session = ServletActionContext.getRequest().getSession();
		String role = session.getAttribute("role").toString();
		int userId = (Integer)session.getAttribute("user"); 
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/javascript;charset=GBK");
		PrintWriter out = response.getWriter();
		
		if(role.equals("student")) {
			Group group = new Group();
			group.setName(name);
			group.setDescription(description);
			group.setIsLock(false);
			Student student = studentService.getStudentById(userId);
			if (student.getGroup()!=null){
				out.println(1);
				return null;
			}
				
			group.setGroupLeader(student);
			if( studentService.createGroup(group) >0 ) {
				student.setGroup(group);
				studentService.updateStudent(student);
				out.println(2);
				return null;
			}
				
			
		}
		out.println(3);
		return null;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getDescription() {
		return description;
	}

	@Resource
	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public StudentService getStudentService() {
		return studentService;
	}

}
